<?php

namespace App\Helpers;

use Modules\CourseEvaluation\Entities\Setting;
use Overtrue\ChineseCalendar\Calendar;

class AcadYearTerm
{
    public $acad_year_term_name;
    public $acad_year_term;
    public $acad_year;
    public $term;
    public $start_acad_year;
    public $end_acad_year;

    public static function AcadYearTerm($data = null)
    {
        $instance = new static();
        $data = self::getAcadYearTerm($data = null);
        $instance->acad_year_term_name = $data['acad_year_term_name'];
        $instance->acad_year_term = $data['acad_year_term'];
        $instance->acad_year = $data['acad_year'];
        $instance->term = $data['term'];
        $instance->end_acad_year = $data['end_acad_year'];
        return $instance;
    }

    /**
     * 说明：根据给定日期获取当前学年学期
     *
     * @param type string $date 给定日期 默认获取当前日期的学年学期 格式：2021-06-22 2021.06.22 2021/06/22
     *
     * @return
     * @author  daixinguo (daixinguo57@163.com)
     */
    public static function getAcadYearTerm($date = null)
    {
        // 由于很多地方都用了这种写法 现在需要扩展后台可设置默认学年学期 所以统一在这里也处理一下
        // 如果后台设置了默认学年学期则使用后台设置的默认学年学期
        $setting = Setting::query()->where('key', 'default_acad_year_term')->first();
        if (!is_null($setting) && !is_null($setting->value)) {
            $acad_year_term = $setting->value;
            $data = self::getAcadYearTermsByShortAcadYearTerm($acad_year_term);
            return $data;
        }

        if (is_null($date)) {
            $date = date("Y-m-d");
        }
        // $date = "2021-12-30";
        // $lunar = new Lunar();
        // $lunar_date = $lunar->convertSolarToLunar($date);
        // $lunar_date_num = $lunar_date[0] . str_pad($lunar_date[4], 2, "0", STR_PAD_LEFT) . str_pad($lunar_date[5], 2, "0", STR_PAD_LEFT);

        if ((bool)preg_match('/-/', $date)) {
            [$year, $month, $date] = explode("-", $date);
        }
        if ((bool)preg_match('/\./', $date)) {
            [$year, $month, $date] = explode(".", $date);
        }
        if ((bool)preg_match('/\//', $date)) {
            [$year, $month, $date] = explode("/", $date);
        }

        $month = sprintf("%02d", $month);
        $date = sprintf("%02d", $date);
        $calendar = new Calendar();

        // 给定日期的当前年份 阳历9月1日时的阴历  此日期节点作为一个上下学期分界
        // $lunar_date_sep = $lunar->convertSolarToLunar($year . "-09-01");
        // $lunar_date_sep_num = $lunar_date_sep[0] . str_pad($lunar_date_sep[4], 2, "0", STR_PAD_LEFT) . str_pad($lunar_date_sep[5], 2, "0", STR_PAD_LEFT);

        if ($month . $date > 820) {
            $acad_year_start = $year;
        } else {
            $acad_year_start = $year - 1;
        }
        $acad_year_end = $acad_year_start + 1;

        $chinese_calendar = $calendar->lunar($year, 1, 15);
        $second_demarcation_y = $chinese_calendar['gregorian_year'];
        $second_demarcation_m = $chinese_calendar['gregorian_month'];
        $second_demarcation_d = $chinese_calendar['gregorian_day'];

        if ($year . $month . $date > $year . "0820") {
            if ($year . $month . $date < ($second_demarcation_y + 1) . $second_demarcation_m . $second_demarcation_d) {
                $term = 1;
            } else {
                $term = 2;
            }
        } else {
            if ($year . $month . $date < $second_demarcation_y . $second_demarcation_m . $second_demarcation_d) {
                $term = 1;
            } else {
                $term = 2;
            }
        }

        // 给定日期阴历年份的元宵 正月十五 以元宵作为一个上下学期分界
        // $lunar_date_sweet_dumplings = $lunar_date[0] . "0115";
        // if ($acad_year_start < $year && $lunar_date_num >= $lunar_date_sweet_dumplings && $lunar_date_num < $lunar_date_sep_num) {
        //     $term = 2;
        // } else {
        //     $term = 1;
        // }

        $data = [
            "acad_year_term_name" => $acad_year_start . "-" . $acad_year_end . "学年第" . $term . "学期",
            "acad_year_term" => $acad_year_start . "-" . $acad_year_end . " " . $term,
            "acad_year" => $acad_year_start . "-" . $acad_year_end,
            "term" => $term,
            "start_acad_year" => $acad_year_start,
            "end_acad_year" => $acad_year_end,
        ];
        return $data;
    }


    /**
     * 说明：给定日期上增加若干个学期 返回区间学年学期
     *
     * @param type string $date 给定日期 默认获取当前日期的学年学期 格式：2021-06-22 2021.06.22 2021/06/22
     * @param type array/int $term_count -2:往前推2个学期 ；2：往后推2个学期； [-2,3]：往前推2个往后推3个学期
     *
     * @return
     * @author  daixinguo (daixinguo57@163.com)
     */
    public static function addTermsByAcadYearTerm($term_count, $date = null)
    {
        if (is_array($term_count)) {
            if ($term_count[0] > 0 || $term_count[1] < 0) {
                // 当为数组时 第一个元素必须是负数 第二个元素必须为正数 表示指定日期的前后学期
                throw new \Exception("参数错误，获取指定日期前后学期时数组参数第一个元素必须为负数，第二个元素必须为正数");
            }
            $before_term_count = $term_count[0];
            $before_term_arr = self::addTermsByAcadYearTerm($before_term_count, $date);
            $later_term_count = $term_count[1];
            $later_term_arr = self::addTermsByAcadYearTerm($later_term_count, $date);
            array_pop($before_term_arr['list']);
            $acad_year_term_arr = $before_term_arr['list'];
            foreach ($later_term_arr['list'] as $value) {
                array_push($acad_year_term_arr, $value);
            }
        } else {
            $now_acad_year_term = self::getAcadYearTerm($date);
            $this_acad_year_term = $now_acad_year_term;
            $now_acad_year_term['is_now'] = 1;
            $acad_year_term_arr = [$now_acad_year_term];
            $data['now'] = $now_acad_year_term;
            $add_term_count = abs($term_count);
            for ($i = 1; $i <= $add_term_count; $i++) {
                if ($term_count < 0) {
                    $mod = ($this_acad_year_term['term'] - 1) % 2;
                    $add_year = $mod == 0 ? -1 : 0;
                } else {
                    $add_year = ($this_acad_year_term['term'] + 1) % 2;
                }
                $acad_year_start = $this_acad_year_term['start_acad_year'] + $add_year;
                $acad_year_end = $this_acad_year_term['end_acad_year'] + $add_year;
                $term = $this_acad_year_term['term'] == 1 ? 2 : 1;
                $this_acad_year_term = [
                    "acad_year_term_name" => $acad_year_start . "-" . $acad_year_end . "学年第" . $term . "学期",
                    "acad_year_term" => $acad_year_start . "-" . $acad_year_end . " " . $term,
                    "acad_year" => $acad_year_start . "-" . $acad_year_end,
                    "term" => $term,
                    "start_acad_year" => $acad_year_start,
                    "end_acad_year" => $acad_year_end,
                    "is_now" => 0,
                ];
                if ($term_count < 0) {
                    array_unshift($acad_year_term_arr, $this_acad_year_term);
                } else {
                    array_push($acad_year_term_arr, $this_acad_year_term);
                }
            }
        }

        $data['list'] = $acad_year_term_arr;
        return $data;
    }

    /**
     * 说明：通过给定的两个学年学期 获取区间的学年学期列表
     *
     * @param type string $frist_acad_year_term  起始学年学期 格式 2020-2021 1
     * @param type string $last_acad_year_term  截止学年学期 格式 2020-2021 2
     *
     * @return
     * @author  daixinguo (daixinguo57@163.com)
     */
    public static function getAcadYearTermsByFristAndLastAcadYearTerm($frist_acad_year_term, $last_acad_year_term)
    {
        $frist_acad_year_term_num = str_replace(" ", "", str_replace("-", "", $frist_acad_year_term));
        $last_acad_year_term_num = str_replace(" ", "", str_replace("-", "", $last_acad_year_term));
        $now_acad_year_term = self::getAcadYearTerm();
        $frist = explode(" ", $frist_acad_year_term);
        $frist_acad_year = explode("-", $frist[0]);
        $term = $frist[1];
        $acad_year_start = $frist_acad_year[0];
        $acad_year_end = $frist_acad_year[1];
        $this_acad_year_term = [
            "acad_year_term_name" => $acad_year_start . "-" . $acad_year_end . "学年第" . $term . "学期",
            "acad_year_term" => $acad_year_start . "-" . $acad_year_end . " " . $term,
            "acad_year" => $acad_year_start . "-" . $acad_year_end,
            "term" => (int)$term,
            "start_acad_year" => (int)$acad_year_start,
            "end_acad_year" => (int)$acad_year_end,
            "is_now" => 0,
        ];
        if ($this_acad_year_term['acad_year_term'] == $now_acad_year_term['acad_year_term']) {
            $this_acad_year_term['is_now'] = 1;
            $data['now'] = $this_acad_year_term;
        }
        if ($frist_acad_year_term_num > $last_acad_year_term_num) {
            // 获取区间学年学期列表时 起始学年学期不能大于截止学年学期
            throw new \Exception("通过起、止学年学期获取区间学年学期列表时 起始学年学期不能大于截止学年学期");
        }
        if ($frist_acad_year_term_num == $last_acad_year_term_num) {
            $acad_year_term_arr = [$this_acad_year_term];
        }
        if ($frist_acad_year_term_num < $last_acad_year_term_num) {
            $acad_year_term_arr = [$this_acad_year_term];
            $acad_year_term_num = $frist_acad_year_term_num;
            while ($acad_year_term_num < $last_acad_year_term_num) {
                $add_year = ($this_acad_year_term['term'] + 1) % 2;
                $acad_year_start = $this_acad_year_term['start_acad_year'] + $add_year;
                $acad_year_end = $this_acad_year_term['end_acad_year'] + $add_year;
                $term = $this_acad_year_term['term'] == 1 ? 2 : 1;

                $this_acad_year_term = [
                    "acad_year_term_name" => $acad_year_start . "-" . $acad_year_end . "学年第" . $term . "学期",
                    "acad_year_term" => $acad_year_start . "-" . $acad_year_end . " " . $term,
                    "acad_year" => $acad_year_start . "-" . $acad_year_end,
                    "term" => $term,
                    "start_acad_year" => $acad_year_start,
                    "end_acad_year" => $acad_year_end,
                    "is_now" => 0,
                ];
                if ($this_acad_year_term['acad_year_term'] == $now_acad_year_term['acad_year_term']) {
                    $this_acad_year_term['is_now'] = 1;
                    $data['now'] = $this_acad_year_term;
                }
                array_push($acad_year_term_arr, $this_acad_year_term);
                $acad_year_term_num = $acad_year_start . $acad_year_end . $term;
            }
        }

        $data['list'] = $acad_year_term_arr;
        return $data;
    }

    /**
     * 说明：通过简写 学年学期获取学年学期数据
     *
     * @param string $short_cad_year_term 格式 2020-2021 1
     *
     * @return
     * @author  daixinguo (daixinguo57@163.com)
     */
    public static function getAcadYearTermsByShortAcadYearTerm($short_cad_year_term)
    {
        $frist = explode(" ", $short_cad_year_term);
        $frist_acad_year = explode("-", $frist[0]);
        $term = $frist[1];
        $acad_year_start = $frist_acad_year[0];
        $acad_year_end = $frist_acad_year[1];
        $this_acad_year_term = [
            "acad_year_term_name" => $acad_year_start . "-" . $acad_year_end . "学年第" . $term . "学期",
            "acad_year_term" => $acad_year_start . "-" . $acad_year_end . " " . $term,
            "acad_year" => $acad_year_start . "-" . $acad_year_end,
            "term" => (int)$term,
            "start_acad_year" => (int)$acad_year_start,
            "end_acad_year" => (int)$acad_year_end,
        ];
        return $this_acad_year_term;
    }
}
